package de.hdodenhof.circleimageview.sample.ui.fragment;

import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.CheckBox;
import android.widget.CompoundButton;
import android.widget.ImageView;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.RequestBuilder;
import com.bumptech.glide.load.resource.drawable.DrawableTransitionOptions;
import com.bumptech.glide.request.target.ViewTarget;
import com.bumptech.glide.request.transition.Transition;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import de.hdodenhof.circleimageview.sample.R;
import de.hdodenhof.circleimageview.sample.ui.fragment.eventbus.PicWrap;

/**
 * A simple {@link Fragment} subclass.
 * Activities that contain this fragment must implement the
 * interface
 * to handle interaction events.
 * Use the {@link PicFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class PicFragment extends Fragment {
    CheckBox mCbHasCache;
    CheckBox mCbCircleCrop;
//    CheckBox mCbCircleCrop;
    View root;
    ImageView imageView;
    TextView mTvLoadCount;
    public static final String PIC_URL = "https://image.baidu.com/search/down?tn=download&word=download&ie=utf8&fr=detail&url=https%3A%2F%2Ftimgsa.baidu.com%2Ftimg%3Fimage%26quality%3D80%26size%3Db9999_10000%26sec%3D1582183788817%26di%3D049d98e557e15f31f45483263cc61d48%26imgtype%3D0%26src%3Dhttp%253A%252F%252Fimg.nga.178.com%252Fattachments%252Fmon_201702%252F14%252FcrQ2g-bg2aXoZ6oT3cS43c-1d4.jpg&thumburl=https%3A%2F%2Fss1.bdstatic.com%2F70cFvXSh_Q1YnxGkpoWK1HF6hhy%2Fit%2Fu%3D3423850083%2C2758871312%26fm%3D26%26gp%3D0.jpg";

    private String url = PIC_URL;

    private  static int mLoadCount;

    /**
     * PicFragment xxx
     */
    public PicFragment() {
        // Required empty public constructor
    }

    /**
     * Use this factory method to create a new instance of
     * this fragment using the provided parameters.
     *
     * @return A new instance of fragment PicFragment.
     */
    // TODO: Rename and change types and number of parameters
    public static PicFragment newInstance() {
        PicFragment fragment = new PicFragment();
        Bundle args = new Bundle();
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

    }

    public void onResume(){
        super.onResume();
        EventBus.getDefault().register(this);
    }

    public void onPause(){
        super.onPause();
        EventBus.getDefault().unregister(this);
    }

    public void onDestroy(){
        super.onDestroy();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        root =  inflater.inflate(R.layout.fragment_pic, container, false);
        imageView = root.findViewById(R.id.image1);
        mCbHasCache = root.findViewById(R.id.cb_has_cache);
        mTvLoadCount = root.findViewById(R.id.tv_load_count);
        mCbHasCache.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                loadImage();
            }
        });
        root.findViewById(R.id.bt_reload).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadImage();
            }
        });
        root.findViewById(R.id.bt_set_backgroud).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                loadBackground();
            }
        });

        return root;
    }

    public View getRoot() {
        return root;
    }

    public void setRoot(View root) {
        this.root = root;
    }

    private void loadImage(){
        loadImage(mCbHasCache.isChecked(), imageView);
    }

    private void loadBackground(){
        imageView.setImageResource(R.drawable.error);
        Glide.with(this).load(url).into(new ViewTarget<View,Drawable>(root) {
            @Override
            public void onResourceReady(@NonNull Drawable resource, @Nullable Transition<? super Drawable> transition) {
                view.setBackground(resource);
            }
        });
    }

    /**
     * 加载图片
     * @param hasCache 是否使用缓存
     * @param imageView 显示图片的组件
     */
    private void loadImage(boolean hasCache, ImageView imageView){
        root.setBackground(new ColorDrawable(Color.TRANSPARENT));
        RequestBuilder<Drawable>  requestBuilder = Glide.with(this.getContext()).load(url).circleCrop();
        requestBuilder.placeholder(R.drawable.hugh);
        requestBuilder.error(R.drawable.error);

        if (!hasCache){
            requestBuilder = requestBuilder.skipMemoryCache(true);
        }
        DrawableTransitionOptions drawableTransitionOptions = new DrawableTransitionOptions();
        drawableTransitionOptions.crossFade();
        requestBuilder.transition(drawableTransitionOptions);
        requestBuilder.into(imageView);
        mLoadCount++;
        mTvLoadCount.setText("图片加载了"+mLoadCount+"次");
    }

    @Subscribe(sticky =true, threadMode = ThreadMode.MAIN)
    public void picUpload(PicWrap picWrap) {
        Log.d("AAA", String.valueOf(picWrap));
        url = picWrap.url;
        loadImage();
    }

}
